<template>
<div class="input-box">
  <input v-bind="$attrs"
         :value="value"
         @blur="validateValue"
         @input="$emit('input',$event.target.value)">
  <p v-show="result.error" class="errorMsg"> {{ result.message }}</p>
</div>
</template>

<script>
const reg = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/
export default {
  name: "mkInput",
  props:['value','rules'],
  inheritAttrs:false,
  data(){
    return{
      result:{
        error:false,
        message:''
      }
    }
  },
  methods:{
    validateValue(){
      let res = this.rules.every(rule => {
        let pass = true
        this.result.message = rule.message || '请输入正确的内容'
        console.log(rule)
        switch (rule.type) {
          case 'required':
            pass = this.value !=="";
            break;
          case "phone":
            pass = reg.test(this.value);
            break
        }
        return pass
      })
      this.result.error = !res
      return res
    }
  },
  mounted() {
    this.$parent.$emit('inputchange',this.validateValue)
  }
}
</script>

<style scoped>
.input-box{
  width: 200px;
  height: 40px;
  background-color: peru;
  display: flex;
  flex-direction: column;
}
.errorMsg{
  color: red;
  font-size: 12px;
  text-align: left;
}
</style>